<?php
namespace heihei\web;

/**
 * 入口路由
 */
class ProjectRoute
{
    protected static function resolveRequestUri()
    {
        $requestUri = '/';
        if(isset($_SERVER['PATH_INFO'])){
            $requestUri = $_SERVER['PATH_INFO'];
        }
        elseif(isset($_SERVER['REQUEST_URI'])){
            $requestUri = $_SERVER['REQUEST_URI'];
        } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
            $requestUri = $_SERVER['ORIG_PATH_INFO'];
        } else {
            die('Unable to determine the request URI.');
        }
        
        return $requestUri;
    }

    public static function getProjectCode(){
        $requestUri = self::resolveRequestUri();
        $requestUri = strpos($requestUri, '?') !== false ? strchr($requestUri, '?', true) : $requestUri;
        $requestUri = trim($requestUri, '/');
        if(!$requestUri){
            return '';
        }
        $scriptFileName = basename($_SERVER['SCRIPT_FILENAME']);
        $requestUriArr = explode($scriptFileName, $requestUri);
        $baseRoute = isset($requestUriArr[1]) && !$requestUriArr[0] ? $requestUriArr[1] : $requestUriArr[0];
        $baseRoute = trim($baseRoute, '/');
        if(strpos($baseRoute, '/') === false){
            return $baseRoute;
        }
        return strchr($baseRoute, '/', true);
    }

    public static function resolveRequestRoute(){
        $projectCode = self::getProjectCode();
        $requestUri = self::resolveRequestUri();
        $_SERVER['REQUEST_URI'] = substr(strchr($requestUri, $projectCode), strlen($projectCode));
        return $projectCode;
    }
}